<template>
  <el-card 
    class="product-card" 
    :body-style="{ padding: '0px' }"
    shadow="hover"
    @click="router.push(`/product/${product.id}`)"
  >
    <div class="image-container">
      <OptimizedImage
        :src="imageUrl"
        :alt="product.name"
        width="100%"
        height="200px"
        @click="handleClick"
      />
      <div v-if="imageError" class="image-placeholder">
        <el-icon><Picture /></el-icon>
        <p>图片加载失败</p>
        <small>{{ product.image }}</small>
      </div>
      <div class="quick-actions">
        <el-button 
          type="primary" 
          :icon="ShoppingCart"
          circle
          @click.stop="handleAddToCart"
        />
        <el-button 
          :icon="isFavorite ? 'Star' : 'StarFilled'" 
          circle 
          @click.stop="handleToggleFavorite"
        />
      </div>
    </div>
    
    <div class="product-info">
      <h3 class="product-name" @click="router.push(`/product/${product.id}`)">
        {{ product.name }}
      </h3>
      <p class="product-desc">{{ truncatedDescription }}</p>
      <div class="product-footer">
        <span class="price">¥{{ Number(product.price).toFixed(2) }}</span>
        <span class="sales">已售 {{ product.sales }}件</span>
      </div>
    </div>
  </el-card>
</template>

<script setup>
import { useRouter } from 'vue-router'
import { ShoppingCart, Star, Picture, Loading } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { ref, inject, computed } from 'vue'
import axios from '../utils/axios'
import OptimizedImage from './OptimizedImage.vue'
import { useProductStore } from '../stores/product'

const router = useRouter()

const props = defineProps({
  product: {
    type: Object,
    required: true,
    default: () => ({
      id: 0,
      name: '',
      description: '',
      price: 0,
      image: '',
      avg_rating: '0.0',
      review_count: 0,
      sales: 0,
      isFavorite: false
    })
  }
})

const imageError = ref(false)
const isFavorite = ref(false)

const headerNavMethods = inject('headerNavMethods')
const productStore = useProductStore()

const imageUrl = computed(() => {
  if (!props.product.image) return '/images/default-product.png'
  return props.product.image
})

const handleAddToCart = async (event) => {
  event.stopPropagation()
  try {
    await axios.post('/api/cart', {
      productId: props.product.id,
      quantity: 1
    })
    ElMessage.success('已添加到购物车')
    if (headerNavMethods) {
      await headerNavMethods.refreshCart()
    }
  } catch (error) {
    console.error('Error:', error)
    if (error.response?.status === 401) {
      ElMessage.error('请先登录')
      router.push('/login')
    } else {
      ElMessage.error('添加失败')
    }
  }
}

const handleToggleFavorite = async (event) => {
  event.stopPropagation()
  try {
    if (!isFavorite.value) {
      await axios.post(`/api/wishlist/${props.product.id}`)
      ElMessage.success('已添加到心愿单')
      isFavorite.value = true
    } else {
      await axios.delete(`/api/wishlist/${props.product.id}`)
      ElMessage.success('已从心愿单移除')
      isFavorite.value = false
    }
    
    if (headerNavMethods) {
      await headerNavMethods.refreshWishlist()
    }
  } catch (error) {
    console.error('Error:', error)
    if (error.response?.status === 400) {
      ElMessage.warning(error.response.data.message)
    } else if (error.response?.status === 401) {
      ElMessage.error('请先登录')
      router.push('/login')
    } else {
      ElMessage.error('操作失败')
    }
  }
}

const handleImageError = (error) => {
  console.error('Image load error:', error);
  console.log('Failed image URL:', props.product.image);
  imageError.value = true;
};

const handleClick = () => {
  productStore.addRecentView(props.product)
  // ... 其他点击处理
}
// 添加在computed部分
const truncatedDescription = computed(() => {
  if (!props.product.description) return '';
  return props.product.description.length > 30 
    ? props.product.description.slice(0, 30) + '...' 
    : props.product.description;
});
</script>

<style scoped>
.product-card {
  cursor: pointer;
  transition: transform 0.2s;
  margin: 10px;
}

.product-card:hover {
  transform: translateY(-5px);
}

.image-container {
  position: relative;
  width: 100%;
  height: 200px;
  overflow: hidden;
}

.product-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.product-card:hover .product-image {
  transform: scale(1.05);
}

.image-placeholder {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  color: #909399;
}

.quick-actions {
  position: absolute;
  bottom: -50px;
  left: 0;
  right: 0;
  display: flex;
  justify-content: center;
  gap: 10px;
  padding: 10px;
  background: rgba(255,255,255,0.9);
  transition: bottom 0.3s ease;
}

.product-card:hover .quick-actions {
  bottom: 0;
}

.product-info {
  padding: 14px;
}

.product-name {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.product-name:hover {
  color: var(--el-color-primary);
}

.product-desc {
  margin: 8px 0;
  font-size: 14px;
  color: #666;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  min-height: 40px;
}

.product-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.price {
  color: #ff6b6b;
  font-size: 18px;
  font-weight: bold;
}

.sales {
  color: #999;
  font-size: 12px;
}
</style> 